﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Bing.Toolkit.Web
{
    public static class UpLoad
    {
        public static List<FileInfomation> SaveFile(string path, bool isRandomPath)
        {
            var httpContext = System.Web.HttpContext.Current;
 
            Func<String, String> fun;

            if (isRandomPath)
            {
                fun = delegate(string s)
                {
                    var str = "";

                    for (var i = 0; i < 3; i++)
                    {
                        var tmp = (Guid.NewGuid().ToString().GetHashCode()).ToString();

                        str += tmp.Substring(tmp.Length - 2) + "/";
                    }

                    if (s.LastIndexOf('/') != s.Length - 1) s += "/";

                    return s + str;
                };
            }
            else
            {
                fun = s => s;
            }

            var list = new List<FileInfomation>();

            for (var i = 0; i < httpContext.Request.Files.Count; i++)
            {
                var file = new FileInfo(httpContext.Request.Files[i].FileName);

                var info = new FileInfomation() 
                {
                    Name = file.Name,
                    FileName = DateTime.Now.ToFileTime() + "."+ file.Extension,
                    FullPath = fun(path),
                    Extension = file.Extension,
                    ContentType = httpContext.Request.Files[i].ContentType,
                    Size = httpContext.Request.Files[i].ContentLength
                };

                var fullName = httpContext.Server.MapPath(info.FullPath + info.FileName);

                var f = new FileInfo(fullName);

                if (!f.Directory.Exists)
                {
                    f.Directory.Create();
                }

                httpContext.Request.Files[i].SaveAs(fullName);


                list.Add(info);

            }

            return list;
        }
    }

    public class FileInfomation
    {
        public Int32 Size { get; set; }
        public String ContentType { get; set; }
        public String Name { get; set; }
        public String FileName { get; set; }
        public String FullPath { get; set; }
        public String Extension { get; set; }
    }
}
